/**
 * 用户相关服务
 */
const util = require('../utils/util.js');
const api = require('../config/api.js');


/**
 * Promise封装wx.checkSession
 */
function checkSession() {
  return new Promise(function(resolve, reject) {
    wx.checkSession({
      success: function() {
        resolve(true);
      },
      fail: function() {
        reject(false);
      }
    })
  });
}

/**
 * Promise封装wx.login
 */
function login() {
  return new Promise(function(resolve, reject) {


    
    wx.login({
      success: function(res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}

/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {

  return new Promise(function(resolve, reject) {
    return login().then((res) => {
      console.log('res.code')
      console.log(res)
      // 获取用户信息
          /* wx.getSetting({
            success: gres => {
              console.log('gres')
              console.log(gres)
              console.log(gres.authSetting['scope.userInfo'])
              if (gres.authSetting['scope.userInfo']) {
                console.log('gresss')
                // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                wx.getUserInfo({
                  success: ires => {

                    console.log('ires')
                    console.log(ires) */
                        //登录远程服务器

                        const userInfo=wx.getStorageSync('userInfo')
                        util.request(api.AuthLoginByWeixin, {
                          code: res.code,
                          userInfo: userInfo
                        }, 'POST').then(subres => {

                            console.log('subres')
                            console.log(subres)
                          if (subres.errno === 0) {
                            //存储用户信息
                            wx.setStorageSync('userInfo', subres.data.userInfo);
                            wx.setStorageSync('token', subres.data.token);

                            resolve(subres);
                          } else {
                            reject(subres);
                          }
                        }).catch((err) => {
                          reject(err);
                        });



                  /* }
                })
              }
            }
          }) */
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  console.log('checkLogin')
  return new Promise(function(resolve, reject) {
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {
      checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });
    } else {
      reject(false);
    }
  });
}

module.exports = {
  loginByWeixin,
  checkLogin,
};